import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/components/pages/Login'
import store from './store'
import { setAuth } from './http'
// import NotFound from '@/components/pages/NotFound'
Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: '/index',
    },
    {
        path: '/index',
        name: 'index',
        component: () => import(/* webpackChunkName: "index" */ '@/components/Main'),
        // children: funcRoutes,
        meta: {
            requireAuth: true
        }
    },
    {
        path: '/login',
        name: 'login',
        component: () => import(/* webpackChunkName: "login" */ '@/components/Login'),
        // children: funcRoutes,
        meta: {
            requireAuth: false
        }
    },
    {
        path: '/preview',
        name: 'preview',
        component: () => import(/* webpackChunkName: "preview" */ '@/components/Preview'),
        // children: funcRoutes,
        meta: {
            requireAuth: true
        }
    },
    {
        path: '*',
        name: '404',
        component: () => import(/* webpackChunkName: "not-found" */ '@/components/NotFound'),
        // children: funcRoutes,
        meta: {
            requireAuth: false
        }
    }

]


if (sessionStorage.getItem("store")) {
    console.log(sessionStorage.getItem("store"))
    store.replaceState(Object.assign({}, store.state, JSON.parse(sessionStorage.getItem("store"))))
    if (store.state.token) {
        setAuth(store.state.token);
    }
}

const router = new VueRouter({
    base: process.env.BASE_URL,
    routes
})

router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {
        // console.log(to.fullPath);
        if (store.state.login && ((new Date()).getTime() - store.state.loginTime) < store.state.second * 1000) {
            next()
        } else {
            next({
                path: '/login', query: {
                    redirect: to.fullPath
                }
            })
        }
    }
    else {
        next()
    }
})

export default router